//
//  AlarmClockViewController.m
//  JiuLe
//
//  Created by 黄鑫 on 16/8/31.
//  Copyright © 2016年 Fine. All rights reserved.
//

#import "AlarmClockViewController.h"
#import "AddClockViewController.h"
#import "BlockUI.h"
#import "CLUIBaseTableViewController+Empty.h"

@interface AlarmClockViewController ()
@property (strong, nonatomic) NSMutableArray *arrDataSource;
@property (strong, nonatomic) UIButton *btn;
@property (strong, nonatomic) UIWindow *widow;
@property (strong, nonatomic) UIToolbar *toolbar;
@end

@implementation AlarmClockViewController
@synthesize widow;

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"提醒与闹钟设置";
    [self showNavgationWithLeftItemWithTitle:@"我的"];
    [self showNavBarWithRightImage:[UIImage imageNamed:@"icon_add"] andRightBtnAction:@selector(addAction) LeftBtnImage:nil andLeftBtnAction:nil title:nil barColor:nil];
    _arrDataSource = [NSMutableArray array];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    if (_arrDataSource.count == 0) {
        [_arrDataSource removeAllObjects];
    }
    [self requestUserInfo];
    [self initToolbar];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:YES];
    widow.hidden = YES;
    [_toolbar removeFromSuperview];

}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:YES];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:YES];
        NSLog(@"1CGRectGetMinX(self.tableView.frame) %f %f",CGRectGetMinY(self.tableView.frame),CGRectGetMaxY(self.tableView.frame));
    if (self.btn == nil) {
        self.tableView.frame = CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 44-64);
        widow = [[UIWindow alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT-44,SCREEN_WIDTH, 44)];
        widow.windowLevel = UIWindowLevelAlert+1;

        [widow addSubview:self.btn];
        [widow makeKeyAndVisible];
    }else{
        widow.hidden = NO;
    }

}

#pragma mark 数据请求
- (void)requestUserInfo{
    [SVProgressHUD showWithStatus:@"获取闹钟信息.." maskType:SVProgressHUDMaskTypeClear];
    WS(weakSelf);
    [[BaseDataRequest alloc] getAlarmClockWithBlock:^(id responseObject, NSString *status, NSError *error) {
        [weakSelf clearLabelEmptyCate];
        [SVProgressHUD dismiss];
        if ([status isEqualToString:@"0"]) {
            _arrDataSource = [responseObject objectForKey:@"result"];
            if(_arrDataSource.count == 0){
                [weakSelf showLabelEmptyCate:CGRectMake((SCREEN_WIDTH - 100)/2, (SCREEN_HEIGHT -140 -64)/2, 100, 100) withTitle:@"这里还没有内容" withImage:[UIImage imageNamed:@"icon_ blank"]];
            }
            [self.tableView reloadData];
        }else{
            [weakSelf showLabelEmptyCate:CGRectMake((SCREEN_WIDTH - 100)/2, (SCREEN_HEIGHT -140 -64)/2, 100, 100) withTitle:@"出错了，稍后再试吧" withImage:[UIImage imageNamed:@"icon_wifi"]];
        }
    }];
}

//闹钟开关
- (void)offAlarmClock:(NSMutableDictionary *)dict with:(BOOL)onOff{
    [SVProgressHUD showWithStatus:@"关闭闹钟.." maskType:SVProgressHUDMaskTypeClear];
    NSString *strCycle = [dict objectForKey:@"clock_cycle"];
    NSMutableDictionary *dictClock = [NSMutableDictionary dictionary];
    dictClock = [dict mutableCopy];
    if (onOff) {
        [dictClock setObject:@"0" forKey:@"isopen"];
    }else{
        [dictClock setObject:@"1" forKey:@"isopen"];
    }
    NSArray *arrCycle = [[dictClock objectForKey:@"clock_cycle"] componentsSeparatedByString:@","];
    [dictClock setObject:arrCycle forKey:@"clock_cycle"];
    [dict setObject:strCycle forKey:@"clock_cycle"];
    [[BaseDataRequest alloc] setAlarmClock:dictClock WithBlock:^(id responseObject, NSString *status, NSError *error) {
        [SVProgressHUD dismiss];
        if ([status isEqualToString:@"0"]) {
        }else{
            if (error != nil) {
                TIPSFORVIEW(@"请检测网络设置");
            }else{
                TIPSFORVIEW([responseObject objectForKey:@"message"]);
            }
        }
    } ];
}

//删除闹钟
- (void)delegateAlarmClock:(NSMutableDictionary *)dictClock{
    [SVProgressHUD showWithStatus:@"删除闹钟.." maskType:SVProgressHUDMaskTypeClear];
    [[BaseDataRequest alloc] delegateAlarmClock:dictClock WithBlock:^(id responseObject, NSString *status, NSError *error) {
        [SVProgressHUD dismiss];
        if ([status isEqualToString:@"0"]) {
            if(_arrDataSource.count == 0){
                WS(weakSelf);
                [weakSelf showLabelEmptyCate:CGRectMake((SCREEN_WIDTH - 100)/2, (SCREEN_HEIGHT -140 -64)/2, 100, 100) withTitle:@"这里还没有内容" withImage:[UIImage imageNamed:@"icon_ blank"]];
            }
        }else{
            if (error != nil) {
                TIPSFORVIEW(@"请检测网络设置");
            }else{
                TIPSFORVIEW([responseObject objectForKey:@"message"]);
            }
        }
    } ];
}

#pragma  mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _arrDataSource.count;
}
 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *identifier = @"AlarmClockViewController0";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier] ;
    }
     UILabel *labName = [cell viewWithTag:1];
     UILabel *labTime = [cell viewWithTag:2];
     UISwitch *witch = [cell viewWithTag:3];
     //UIImageView *imageV = [cell viewWithTag:5];
     NSMutableDictionary *dicr = _arrDataSource[indexPath.row];
     labName.text = [dicr objectForKey:@"clock_mark"];
     labTime.text = [dicr objectForKey:@"clock_time"];
     if ([[dicr objectForKey:@"isopen"] isEqualToString:@"1"]) {
         witch.on = YES;
     }else{
         witch.on = NO;
     }
    WS(weakSelf)
    [witch handleControlEvent:UIControlEventTouchUpInside withBlock:^(id sender) {
        if (witch.on) {
            [weakSelf offAlarmClock:dicr with:NO];
        }else{
            [weakSelf offAlarmClock:dicr with:YES];
        }
    }];
    return cell;
}

#pragma mark - UITableview Delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
     AddClockViewController *addClock = [[UIStoryboard storyboardWithName:@"PersonalViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"AddClockViewController"];
    addClock.clockVCType =  ClockVCTypeEdit;
    addClock.dict = _arrDataSource[indexPath.row];
     [self.navigationController pushViewController:addClock animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 15;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (editingStyle ==UITableViewCellEditingStyleDelete) {
        if (indexPath.row<[self.arrDataSource count]) {
            NSMutableDictionary *dicClock = _arrDataSource[indexPath.row];
            [dicClock removeObjectForKey:@"clock_asyn"];
            [dicClock removeObjectForKey:@"clock_cycle"];
            [dicClock removeObjectForKey:@"clock_mark"];
            [dicClock removeObjectForKey:@"clock_time"];
            [dicClock removeObjectForKey:@"isopen"];
            [self delegateAlarmClock:dicClock];
            [self.arrDataSource removeObjectAtIndex:indexPath.row];
            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];
        }
    }
}

#pragma  mark - 
- (void)addAction{
    AddClockViewController *addClock = [[UIStoryboard storyboardWithName:@"PersonalViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"AddClockViewController"];
    addClock.clockVCType = ClockVCTypeAdd;
    UINavigationController *presNavigation = [[UINavigationController alloc] initWithRootViewController: addClock];
    [self presentViewController:presNavigation animated:YES completion:nil];
}

- (void)initToolbar{
    self.btn = [[UIButton alloc] initWithFrame:CGRectMake(30,1,SCREEN_WIDTH-60, 38)];
    [self.btn setBackgroundColor:RGB(89, 199, 232)];
    [self.btn setTitle:@"同步数据" forState:UIControlStateNormal];
    self.btn.layer.cornerRadius = 6;
    self.btn.layer.masksToBounds = YES;
    UIBarButtonItem *leftItem =[ [UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    UIBarButtonItem *rightItem =[ [UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    UIBarButtonItem *btn1=[[UIBarButtonItem alloc] initWithCustomView:self.btn];
    _toolbar=[[UIToolbar alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 40,SCREEN_WIDTH, 40)];
    NSArray *arr1=[[NSArray alloc]initWithObjects:leftItem,btn1,rightItem, nil];
    _toolbar.items = arr1;
    _toolbar.clipsToBounds = YES;
    [[UIApplication sharedApplication].keyWindow addSubview:_toolbar];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
